<?php defined('SYSPATH') OR die('No direct access allowed.');

class Category_Model extends ORM_Tree{

 public $parent_column='parent_id';
 protected $has_many = array('media');
 protected $children = "categories";
 protected $sorting = array('title' => 'asc');
 

	public function before_delete(){
		foreach($this->media as $media){
			$media->delete();
		}
	}


	public function get_ancestors(){
		$rarray=array();
		$pid=$this->parent_id;		
		while($pid!='0'){	
			$parent=ORM::factory('category', $pid);
			$pid=$parent->parent_id;
			$rarray[]=$parent;
		}
		$rarray=array_reverse($rarray);
		return $rarray;
	}
	
	public function get_openones(){	
		$rarray=array($this->id);
		$pid=$this->parent_id;		
		while($pid!='0'){	
			$parent=ORM::factory('category', $pid);
			$rarray[]=$parent->id;
			$pid=$parent->parent_id;
			
		}
		return $rarray;
	}
	
	public function get_pulldown_list($firstpoints=NULL){
		$allpages=ORM::factory('category');
		$pages=$allpages->orderby(array('parent_id'=>'', 'position'=>''))->find_all()->as_array();
		//$list=array('0'=>'root');
	
		$list=array();
		if($firstpoints){
			$list+=$firstpoints;
		}
		
		$list+=$this->get_nested_pulldown_list($pages,'0', '1');
		
		return $list;
	}
	
	public function get_nested_pulldown_list ($categories, $parent_id, $step){
		$array=array();
		foreach($categories as $onecat){			
			if($onecat->parent_id==$parent_id){
				$str='';
				for($i=0;$i<$step;$i++){
					$str.='&nbsp;&nbsp;&nbsp;&nbsp;';
				}
				if($onecat->id!=$this->id){
					$array[$onecat->id]=$str.$onecat->title;
					$array+=$this->get_nested_pulldown_list($categories, $onecat->id, $step+1);			
				}
			}			
		}
		return $array;
	}


}



